package com.xiaomi.dao.impl;

import com.xiaomi.dao.ItemDao;
import com.xiaomi.entity.Item;
import com.xiaomi.entity.Product;
import com.xiaomi.utils.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/26
 */
public class ItemDaoImpl implements ItemDao {
    private final QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public int insertItem(Item item) throws Exception {
        Object[] objects = {item.getPid(), item.getOid(), item.getNum(), item.getMoney()};
        String sql = "insert into item values(default,?,?,?,?)";
        return queryRunner.update(sql, objects);
    }

    @Override
    public List<Item> itemList(String oid) throws Exception {
        String sql = "select * from item i,product p where i.pid=p.pid and i.oid=?";
        List<Map<String, Object>> maps = queryRunner.query(sql, new MapListHandler(), oid);
        if (maps != null) {
            List<Item> items = new ArrayList<>();
            for (Map<String, Object> map : maps) {
                Item item = new Item();
                Product product = new Product();
                BeanUtils.populate(item, map);
                BeanUtils.populate(product, map);
                item.setProduct(product);
                items.add(item);
            }
            return items;
        }
        return null;
    }
}
